import psutil
import json
import re
import subprocess
import time
import os

def getProcess(process_name):
    # 获取所有正在运行的进程
    processes = psutil.process_iter()

    isfind = False

    # 遍历所有进程，打印进程信息
    for process in processes:
        name = process.name()
        if name.find("ffmpeg") >= 0:
            cmdline = process.cmdline()
            if cmdline[4].find(process_name) > 0:
                isfind = True
            print(f"进程名：{name}")


    if isfind == False:
        os.system('/usr/bin/ffmpeg -nostdin -re -rtsp_transport tcp -i '+process_name+' -hls_wrap 10 -c copy -f hls /tmp/'+process_name+'.m3u8 &')

def getData():
    allsite = []
    with open("site.json", 'r', encoding="utf-8") as f:
        line = f.readline()
        while line:
            if line != None:
                content = line.lstrip().replace(" ", "").replace(",", "")
                if content.find("cdtf") > 0:
                    pattern = r'\"(.*?)\"'
                    matches = re.findall(pattern, content)
                    allsite.append(matches[1])
            line = f.readline()
        return allsite

while 1:
    allsit = getData()
    i = 1
    for site in allsit:
        piece = str(site).split("/")
        flowname = piece[3]
        getProcess(flowname)
    time.sleep(3)



